package com.yuncheng.spcyApi.flowController;

import com.yuncheng.vo.CurrentUserVo;
import com.yuncheng.vo.HttpResult;
import org.apache.commons.collections.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuncheng.spcyApi.alog.annotation.Log;
import com.yuncheng.spcyApi.busService.BusService;
import com.yuncheng.spcyApi.busService.MyJbxxService;
import com.yuncheng.common.base.controller.BaseController;
import com.yuncheng.spcyApi.constant.common.LogConstant;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.constant.flow.FlowConstant;
import com.yuncheng.spcyApi.constant.flow.YlqxFlowConstant;
import com.yuncheng.spcyApi.constant.flow.YpscFlowConstant;
import com.yuncheng.spcyApi.entity.*;
import com.yuncheng.spcyApi.flowService.*;
import com.yuncheng.spcyApi.mapper.SpcyFlowMapper;
import com.yuncheng.spcyApi.selectXzxkApi.constant.PutZwxtConstant;
import com.yuncheng.spcyApi.service.*;
import com.yuncheng.spcyApi.utils.GetCurrentUserUtils;

import com.yuncheng.spcyApi.vo.common.OrderItemVo;
import com.yuncheng.spcyApi.vo.common.Result;
import com.yuncheng.spcyApi.vo.common.StartEndTimeVo;
import com.yuncheng.spcyApi.vo.flow.AgentVo;
import com.yuncheng.spcyApi.vo.flow.YpscFlowVo;
import com.yuncheng.spcyApi.vo.spcy.SpcyFlowVo;
import com.yuncheng.spcyApi.vo.spcy.SpcyReturnVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;
import utils.LogUtils;
import utils.ObjectToMapUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 审评查验-申请事项基本信息
 * @Author: csx
 * @Date: 2023-03-03
 * @Version: V1.0
 */
//@Api(tags = "审评查验-药品生产流程接口")
@RestController
@RequestMapping("/api/spzx-spcy/flow-ypsc")
public class SpcyFlowYpscController extends BaseController<SpcySqsxBasic, ISpcySqsxBaiscService> {

    private static final Logger log = LoggerFactory.getLogger(SpcyFlowYpscController.class);

    @Resource
    private ISpcySqsxBaiscService spcySqsxBaiscService;

    @Resource
    private SpcyFlowMapper spcyFlowMapper;

    @Resource
    private BusService busService;

    @Resource
    private ISpcySqsxJobService spcySqsxJobService;

    @Resource
    private ISpcyLogService spcyLogService;

    @Resource
    @Lazy
    private YpscFlowService ypscFlowService;

    @Resource
    @Lazy
    private YpzcFlowService ypzcFlowService;

    @Resource
    @Lazy
    private YpltFlowService ypltFlowService;

    @Resource
    @Lazy
    private YlqxFlowService ylqxFlowService;

    @Resource
    @Lazy
    private HzpFlowService hzpFlowService;

    @Resource
    @Lazy
    private MyJbxxService myJbxxService;


    @Log(title = "流程监控-分页查询")
    @ApiOperation(value = "流程监控-分页查询")
    @GetMapping("flowJkPage")
    public HttpResult<?> flowJkPage(
            SpcyFlowVo spcyFlowVo,
            @RequestParam(name = "bjzt",defaultValue = "") String bjzt,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(name = "onlyCurrentUser", defaultValue = "false") boolean onlyCurrentUser,
            OrderItemVo orderItemVo){
        CurrentUserVo user = GetCurrentUserUtils.getCurrentUser();
        if (user == null){
            return HttpResult.error("请重新登录，Token已失效！");
        }

        if (StringUtils.isNotBlank(spcyFlowVo.getSfcxgr()) && spcyFlowVo.getSfcxgr().equals("否")){
            onlyCurrentUser = false;
        }

       /* String flowName = "";
        if (StringUtils.isNotBlank(spcyFlowVo.getFywflcode())){
            FlowConstant flowConstant = SpcyConstant.getFlowConstant(spcyFlowVo.getFywflcode());
            spcyFlowVo.setFlcmc(flowConstant.getFlowName());
        }*/

       if (StringUtils.isNotBlank(bjzt)){
           if (bjzt.equals("所有")){
               spcyFlowVo.setBjlc("是");
           }
           if (bjzt.equals("办结")) {
               spcyFlowVo.setFlczt(YpscFlowConstant.HJMC_LCJS);
           }
           if (bjzt.equals("撤件")){
               spcyFlowVo.setFlczt(PutZwxtConstant.SQSX_LCZT_QYCJ);
           }
           if (bjzt.equals("非中心事项")){
               spcyFlowVo.setFlczt(PutZwxtConstant.SQSX_LCZT_FZXBLSX);
           }
       }

        /*if (StringUtils.isBlank(spcyFlowVo.getFblzt()) && StringUtils.isBlank(bjzt)){
            spcyFlowVo.setFblzt(SpcyConstant.BLZT_DB);
        }*/

        Page<SpcyFlowVo> page = new Page<>(pageNo, pageSize);
        spcyFlowVo.setFlcmc(YpscFlowConstant.LCMC_LIKE_SPCYLC);
        IPage<SpcyFlowVo> list = spcyFlowMapper.flowJkPage(page,onlyCurrentUser,user,spcyFlowVo,orderItemVo);
        return HttpResult.ok(list);
    }

    @Log(title = "分页查询-移送数据")
    @ApiOperation(value = "分页查询-移送数据")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "bzzt",value = "补正状态(0: 所有、1:补正中、2:补正完成)"),
            @ApiImplicitParam(name = "zgzt",value = "整改状态(0: 所有、1:整改中、2:整改完成)")
    })
    @GetMapping(value = "querySqsxYsDataPageList")
    public HttpResult<?> querySqsxYsDataPageList(SpcySqsxBasic sqsx,
                                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                 @RequestParam(name = "bzzt", defaultValue = "0") String bzzt,
                                                 @RequestParam(name = "zgzt", defaultValue = "0") String zgzt,
                                                 @RequestParam(name = "onlyCurrentUser", defaultValue = "true") boolean onlyCurrentUser){

        Page<SpcySqsxBasic> page = new Page<>(pageNo,pageSize);
        LambdaQueryWrapper<SpcySqsxBasic> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(StringUtils.isNotBlank(sqsx.getFywflcode()),SpcySqsxBasic::getFywflcode,sqsx.getFywflcode());
        queryWrapper.like(StringUtils.isNotBlank(sqsx.getFqymc()),SpcySqsxBasic::getFqymc,sqsx.getFqymc());
        queryWrapper.like(StringUtils.isNotBlank(sqsx.getFsxmc()),SpcySqsxBasic::getFsxmc,sqsx.getFsxmc());
        queryWrapper.like(StringUtils.isNotBlank(sqsx.getFjclx()),SpcySqsxBasic::getFjclx,sqsx.getFjclx());
        queryWrapper.like(StringUtils.isNotBlank(sqsx.getFslbh()),SpcySqsxBasic::getFslbh,sqsx.getFslbh());
        queryWrapper.like(StringUtils.isNotBlank(sqsx.getFsqdbh()),SpcySqsxBasic::getFsqdbh,sqsx.getFsqdbh());
        queryWrapper.like(StringUtils.isNotBlank(sqsx.getFcpmc()),SpcySqsxBasic::getFcpmc,sqsx.getFcpmc());

        // 事项-流程状态
        if (StringUtils.isNotBlank(sqsx.getFlczt())){
            queryWrapper.eq(StringUtils.isNotBlank(sqsx.getFlczt()),SpcySqsxBasic::getFlczt,sqsx.getFlczt());
        }else {
            queryWrapper.isNotNull(SpcySqsxBasic::getFlczt);
        }

        if (sqsx.getFcykssj() != null){
            queryWrapper.ge(SpcySqsxBasic::getFcykssj,sqsx.getFcykssj());
        }
        if (sqsx.getFcyjssj() != null){
            queryWrapper.le(SpcySqsxBasic::getFcyjssj,sqsx.getFcyjssj());
        }

        if (StringUtils.isNotBlank(bzzt) && !bzzt.equals("0")){
            queryWrapper.eq(SpcySqsxBasic::getFzwxtbzzt, bzzt);
        }

        if (StringUtils.isNotBlank(zgzt) && !zgzt.equals("0")){
            queryWrapper.eq(SpcySqsxBasic::getFzwxtzgzt, zgzt);
        }

        Page<SpcySqsxBasic> page1 = spcySqsxBaiscService.page(page, queryWrapper);
        return HttpResult.ok(page1);
    }

    @Log(title = "分页查询-查询统计数据")
    @ApiOperation(value = "分页查询-查询统计数据")
    @GetMapping(value = "querySqsxStatTjPageList")
    public HttpResult<?> querySqsxStatTjPageList(SpcySqsxBasic sqsx,
                                                 @RequestParam(name = "isEnd",defaultValue = "true")boolean isEnd,
                                                 @RequestParam(name = "fhjmc",defaultValue = "")String fhjmc,
                                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                 OrderItemVo orderItemVo){
        boolean onlyCurrentUser = false;
        CurrentUserVo user = GetCurrentUserUtils.getCurrentUser();
        if (user == null){
            return HttpResult.error("请重新登录，Token已失效！");
        }
        SpcyFlowVo spcyFlowVo = new SpcyFlowVo();
        spcyFlowVo.setFywflcode(sqsx.getFywflcode());

        spcyFlowVo.setFsxmc(sqsx.getFsxmc());
        spcyFlowVo.setFqymc(sqsx.getFqymc());
        spcyFlowVo.setFsqdbh(sqsx.getFsqdbh());
        spcyFlowVo.setFslbh(sqsx.getFslbh());
        spcyFlowVo.setFjclx(sqsx.getFjclx());
        spcyFlowVo.setFcykssj(sqsx.getFcykssj());
        spcyFlowVo.setFcyjssj(sqsx.getFcyjssj());

        if (StringUtils.isBlank(fhjmc)){
            isEnd = true;
        }else {
            isEnd = false;
            spcyFlowVo.setFhjmc(fhjmc);
            spcyFlowVo.setFblzt(SpcyConstant.BLZT_DB);
        }

        // 查询是否结束
        if (isEnd){
//            spcyFlowVo.setFlczt(SpcyConstant.LCZT_LCJS); // 流程结束
            spcyFlowVo.setBjlc("是");
        }else {
            spcyFlowVo.setLcsfjs("否"); // 流程未结束
        }
        Page<SpcyFlowVo> page = new Page<>(pageNo, pageSize);
        IPage<SpcyFlowVo> list = spcyFlowMapper.flowJkPage(page,onlyCurrentUser,user,spcyFlowVo,orderItemVo);
        return HttpResult.ok(list);
    }

    @Log(title = "统计数据")
    @ApiOperation(value = "统计数据")
    @GetMapping(value = "queryTjData")
    public HttpResult<?> queryTjData(@RequestParam(value = "fywflcode",defaultValue = "")String fywflcode, StartEndTimeVo startEndTimeVo){
        Map map = new HashMap();

        map.putAll(myJbxxService.queryDeptFlowTjData(startEndTimeVo,fywflcode));

        return HttpResult.ok(map);
    }

    @Log(title = "经办人-数据修订-流程任务")
    @ApiOperation(value = "经办人-数据修订-流程任务")
    @GetMapping(value = "flowJobSjxd")
    public HttpResult<?> flowJobSjxd(SpcyFlowVo spcyFlowVo,
                                     @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                     @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                     @RequestParam(name = "onlyCurrentUser", defaultValue = "false") boolean onlyCurrentUser,
                                     OrderItemVo orderItemVo){
        CurrentUserVo user = GetCurrentUserUtils.getCurrentUser();
        if (user == null){
            return HttpResult.error("请重新登录，Token已失效！");
        }
        Page<SpcyFlowVo> page = new Page<>(pageNo, pageSize);
        spcyFlowVo.setFblzt(SpcyConstant.BLZT_DB);
        spcyFlowVo.setFzbr(user.getId());
        spcyFlowVo.setLcsfjs("否");
        spcyFlowVo.setFlcmc(YpscFlowConstant.LCMC_LIKE_SPCYLC);
        onlyCurrentUser = false;
        IPage<SpcyFlowVo> list = spcyFlowMapper.flowJkPage(page,onlyCurrentUser,user,spcyFlowVo,orderItemVo);
        return HttpResult.ok(list);
    }


    @Log(title = "流程列表-分页查询")
    @ApiOperation(value = "流程列表-分页查询")
    @GetMapping("flowJobPage")
    public HttpResult<?> flowJobPage(
            SpcyFlowVo spcyFlowVo,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(name = "onlyCurrentUser", defaultValue = "true") boolean onlyCurrentUser,OrderItemVo orderItemVo){
        CurrentUserVo user = GetCurrentUserUtils.getCurrentUser();
        if (user == null){
            return HttpResult.error("请重新登录，Token已失效！");
        }

        if (StringUtils.isNotBlank(spcyFlowVo.getSfcxgr()) && spcyFlowVo.getSfcxgr().equals("否")){
            onlyCurrentUser = false;
        }

        if (StringUtils.isBlank(spcyFlowVo.getFblzt())){
            spcyFlowVo.setFblzt(SpcyConstant.BLZT_DB);
        }

        Page<SpcyFlowVo> page = new Page<>(pageNo, pageSize);
        spcyFlowVo.setFlcmc(YpscFlowConstant.LCMC_LIKE_SPCYLC);
        IPage<SpcyFlowVo> list = spcyFlowMapper.flowJobPage(page,onlyCurrentUser,user,spcyFlowVo,orderItemVo);
        return HttpResult.ok(list);
    }

    @Log(title = "获取第一个环节待办人")
    @ApiOperation(value = "获取第一个环节待办人")
    @GetMapping(value = "queryFirstNodeDbr")
    public HttpResult<?> queryFirstNodeDbr(@RequestParam(value = "fywflcode",defaultValue = "")String fywflcode){
        if (StringUtils.isBlank(fywflcode)){
            return HttpResult.error("业务分类编码不能为空");
        }
        /*Map map = new HashMap();
        Map firstNodeDbr = busService.getFirstNodeDbr(fywflcode);
        map.putAll(firstNodeDbr);*/
        return HttpResult.ok();
    }

    @Log(title = "查询当前流程任务详情-通过当前流程任务id")
    @ApiOperation(value = "询当前流程任务详情-通过当前流程任务id")
    @ApiImplicitParam(value = "jobid",name = "流程任务id",required = true)
    @GetMapping(value = "queryJobByJobId")
    public HttpResult<?> queryJobByJobId(@RequestParam(value = "jobid",defaultValue = "")String jobid){
        log.info("queryJobByJobId: -----{}",jobid);
        if (StringUtils.isBlank(jobid)){
            return HttpResult.error("流程任务参数为空！");
        }
        Map map = busService.getJobConcernByJobId(jobid);
        log.info("queryJobByJobId{}",map);
        return HttpResult.ok(map);
    }

    @Log(title = "删除流程-通过流程任务id")
    @ApiOperation(value = "删除流程-通过流程任务id")
    @ApiImplicitParam(value = "jobids",name = "流程任务ids,逗号分割",required = true)
    @DeleteMapping(value = "/deleteFlowJob")
    public HttpResult<?> deleteFlowJob(@RequestParam("jobids")String jobids){
        List<String> jobidList = Arrays.asList(jobids.split(","));
        if (CollectionUtils.isNotEmpty(jobidList)){
            for (String id : jobidList) {
                SpcySqsxJob job = spcySqsxJobService.getById(id);
                if (job == null){
                    log.error("删除流程-通过流程任务id：出错{}id为空，流程不存在。",id);
                    continue;
                }
                spcySqsxJobService.removeById(id);

                // 删除申请事项
                SpcySqsxBasic sqsx = spcySqsxBaiscService.getById(job.getFpid());
                if (sqsx != null) {
                    boolean flag = spcySqsxBaiscService.removeById(job.getFpid());// 删除申请事项
                    if (flag) {
                        String log = "";
                        log += LogUtils.MapToStringMethod(ObjectToMapUtils.objectToMap(sqsx));
                        spcyLogService.addLogs(job.getFhjmc(), log, job.getFpid(), LogConstant.LOGS_SQSX_JOB, SpcyConstant.LOGS_SYS_TYPE_SC);
                    }
                }

                String lognr = "删除申请事项-流程: ";
                Map<String, Object> jobMap = ObjectToMapUtils.objectToMap(job);
                lognr += LogUtils.MapToStringMethod(jobMap);
                spcyLogService.addLogs(job.getFhjmc(),lognr,job.getFpid(), LogConstant.LOGS_SQSX_JOB, SpcyConstant.LOGS_SYS_TYPE_SC);
            }
        }

        return HttpResult.ok("删除成功");
    }

    @Log(title = "初始化申请事项流程任务")
    @ApiOperation(value = "初始化成功申请事项流程任务")
    @GetMapping(value = "initFlowJob")
    public HttpResult<?> initFlowJob(@RequestParam("sqsxid")String sqsxid){
        CurrentUserVo currentUser = GetCurrentUserUtils.getCurrentUser();
        if (currentUser == null){
            return HttpResult.error("登录已失效，请重新登录");
        }
        SpcySqsxBasic sqsx = spcySqsxBaiscService.getById(sqsxid);
        if (sqsx != null){
            List<SpcySqsxJob> jobList = spcySqsxJobService.list(new LambdaQueryWrapper<SpcySqsxJob>().eq(SpcySqsxJob::getFpid, sqsxid));
            if (CollectionUtils.isEmpty(jobList)){
                Result result = null;
                if (StringUtils.isNotBlank(sqsx.getFywflcode()) && sqsx.getFywflcode().equals(SpcyConstant.YWFL_CODE_YPSC)) {
                     result = ypscFlowService.initJob(sqsxid, currentUser);
                }else if (StringUtils.isNotBlank(sqsx.getFywflcode()) && sqsx.getFywflcode().equals(SpcyConstant.YWFL_CODE_YPZC)) {
                    result = ypzcFlowService.initJob(sqsxid, currentUser);
                }else if (StringUtils.isNotBlank(sqsx.getFywflcode()) && sqsx.getFywflcode().equals(SpcyConstant.YWFL_CODE_YPJY)) {
                    result = ypltFlowService.initJob(sqsxid, currentUser);
                }else if (StringUtils.isNotBlank(sqsx.getFywflcode()) && sqsx.getFywflcode().equals(SpcyConstant.YWFL_CODE_YLQX)) {
                    result = ylqxFlowService.initJob(sqsxid, currentUser);
                }else if (StringUtils.isNotBlank(sqsx.getFywflcode()) && sqsx.getFywflcode().equals(SpcyConstant.YWFL_CODE_HZP)) {
                    result = hzpFlowService.initJob(sqsxid, currentUser);
                }else if (StringUtils.isNotBlank(sqsx.getFywflcode()) && sqsx.getFywflcode().equals(SpcyConstant.YWFL_CODE_YPZCLC)) {
                    result = ypzcFlowService.initJob(sqsxid, currentUser);
                }
                if (!result.isSuccess()){
                    return HttpResult.error(result.getMessage());
                }
            }else {
                return HttpResult.error("该事项已经初始化了");
            }
        }
        return HttpResult.ok("初始化成功");
    }


    @Log(title = "药品生产流程保存接口")
    @ApiOperation(value = "药品生产流程保存接口")
    @PostMapping(value = "/saveFlow")
    public HttpResult<?> saveFlow(@RequestBody YpscFlowVo ypscFlowVo) {
        String submitType = YpscFlowConstant.SUBMIT_TYPE_SAVE; // 保存
        String jobId = ypscFlowVo.getJobid(); // 当前流程任务id
        String sqsxid = ypscFlowVo.getSqsxid(); // 当前申请事项id
        String opinion = ypscFlowVo.getOpinion(); // 办理意见

        if (StringUtils.isBlank(sqsxid)){
            return HttpResult.error("申请事项id参数丢失，请联系管理员");
        }
        if (StringUtils.isBlank(jobId)){
            return HttpResult.error("流程任务id参数丢失，请联系管理员");
        }

        // 流程处理
        Result httpResult = ypscFlowService.handleFlow(ypscFlowVo,  jobId, sqsxid, submitType, opinion);
        if (!httpResult.isSuccess()){
            return HttpResult.error(httpResult.getMessage());
        }

        Map map = new HashMap();
        HttpResult<Object> res = new HttpResult<>(true);
        res.setMessage("保存成功");
        Map jobConcernByJobId = busService.getJobConcernByJobId(jobId);
        map.putAll(jobConcernByJobId);

        res.setResult(map);
        return res;
    }


    @Log(title = "药品生产流程提交接口")
    @ApiOperation(value = "药品生产流程提交接口")
    @PostMapping(value = "/submitFlow")
    public HttpResult<?> submitFlow(@RequestBody YpscFlowVo ypscFlowVo) {
        String submitType = YpscFlowConstant.SUBMIT_TYPE_SUBMIT; // 提交

        String jobId = ypscFlowVo.getJobid();
        String sqsxid = ypscFlowVo.getSqsxid();
        String opinion = ypscFlowVo.getOpinion();
        if (StringUtils.isBlank(sqsxid)){
            return HttpResult.error("申请事项id参数丢失，请联系管理员");
        }

        if (StringUtils.isBlank(jobId)){
            return HttpResult.error("流程任务id参数丢失，请联系管理员");
        }

       /* if (StringUtils.isBlank(opinion)){
            return HttpResult.error("请填写办理意见");
        }*/



        Result httpResult1 = ypscFlowService.handleFlow(ypscFlowVo,  jobId, sqsxid, submitType, opinion);
        if (!httpResult1.isSuccess()){
            return HttpResult.error(httpResult1.getMessage());
        }

        return HttpResult.ok("提交成功");
    }


    @Log(title = "获取已办列表-通过当前流程id")
    @ApiOperation(value = "获取已办列表-通过当前流程id")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "jobid",value = "流程任务id"),
            @ApiImplicitParam(name = "isZdhj",value = "是否指定环节，默认：false，不指定")
    })
    @GetMapping(value = "queryAllYbJob")
    public HttpResult<?> queryAllYbJob(@RequestParam(value = "jobid",defaultValue = "")String jobid,
                                          @RequestParam(value = "isZdhj",defaultValue = "false")boolean isZdhj){

        List<Map<String, String>> currentJobPrevious = ypscFlowService.getCurrentJobPrevious(jobid, isZdhj);
        return HttpResult.ok(currentJobPrevious);
    }


    @Log(title = "现场检查模式-退回上一个环节")
    @ApiOperation(value = "现场检查模式-退回上一个环节")
    @PostMapping(value = "returnUpperXcjcFlowJob")
    public HttpResult<?> returnUpperXcjcFlowJob(@RequestBody SpcyReturnVo spcyReturnVo){
        ypscFlowService.returnZdJob(spcyReturnVo);
        return HttpResult.ok("退回成功");
    }

    /**
     * 废弃退回功能
     */
    public HttpResult<?> returnUpperXcjcFlowJobOld(@RequestBody Map<String,String> map){
        String jobid = map.get("jobid");
        String opinion = map.get("opinion");
        String shjid = map.get("shjid");

        CurrentUserVo currentUser = GetCurrentUserUtils.getCurrentUser();
        if (currentUser == null){
            return HttpResult.error("登录已失效，请重新登录");
        }
        SpcySqsxJob job = spcySqsxJobService.getById(jobid);
        // 待办-获取上一个环节id
        SpcySqsxJob syhjJob = spcySqsxJobService.getById(shjid);
        if (job == null){
            return HttpResult.error("当前流程任务不存在");
        }
        if (syhjJob == null){
            return HttpResult.error("当前选择退回的环节不存在");
        }
        // 办理状态 - 待办
        if (StringUtils.isNotBlank(job.getFblzt()) && (job.getFblzt().equals(SpcyConstant.BLZT_DB)
                || job.getFblzt().equals(SpcyConstant.BLZT_TH))) {
            String oldshjid = job.getFsyhjid(); // 当前流程上环节

            // 如果 当前 流程上环节与 选择 退回的环节 相等 则删除.否则不等，则修改办理状态
            if (!oldshjid.equals(shjid)){
                this.dealDelNodeJob(shjid);
            }
            if (syhjJob.getFhjmc().equals(YpscFlowConstant.HJMC_FAZZ)){
                SpcySqsxBasic sqsx = spcySqsxBaiscService.getById(job.getFpid());
                if (sqsx != null){
                    sqsx.setFcyfazt("否");
                    sqsx.setFspfazt("否");
                    spcySqsxBaiscService.updateById(sqsx);
                }
            }
            syhjJob.setFthyj(opinion);
            syhjJob.setFfssj(new Date());
            syhjJob.setFblzt(SpcyConstant.BLZT_TH);
            syhjJob.setFfsrid(currentUser.getId());
            syhjJob.setFfsrmc(currentUser.getName());
            boolean flag = spcySqsxJobService.updateById(syhjJob);
            if (flag){
                // 发送退回短信
                String nextNodeSmsContent = busService.getNextNodeSmsContent(syhjJob, null);
                busService.sendNextNodeSmsContent(syhjJob,nextNodeSmsContent);
            }

            spcySqsxJobService.removeById(jobid); // 删除当前流程任务待办
        }

        String logNr = "退回上一环节: 从["+job.getFhjmc()+"]退回到["+syhjJob.getFhjmc()+"];";
        Map<String, Object> logMap = ObjectToMapUtils.objectToMap(job);
        logNr += LogUtils.MapToStringMethod(logMap);
        spcyLogService.addLogs(job.getFhjmc(),logNr,job.getFpid(), LogConstant.LOGS_SQSX_JOB,SpcyConstant.LOGS_SYS_TYPE_TH);

        return HttpResult.ok("退回成功");
    }

    /** 递归删除当前流程任务父级的所有流程任务（现场检查/技术审评） */
    public String dealDelNodeJob(String shjid){
        String id = "";
        List<SpcySqsxJob> shjList = spcySqsxJobService.list(new LambdaQueryWrapper<SpcySqsxJob>().eq(SpcySqsxJob::getFsyhjid, shjid));
        if (CollectionUtils.isNotEmpty(shjList)){
            for (SpcySqsxJob job : shjList) {
                id = job.getId();
                if (job.getFhjmc().equals(YpscFlowConstant.HJMC_FAZZ)) {
                    SpcySqsxBasic sqsx = spcySqsxBaiscService.getById(shjList.get(0).getFpid());
                    if (sqsx != null) {
                        sqsx.setFcyfazt("否");
                        sqsx.setFspfazt("否");
                        spcySqsxBaiscService.updateById(sqsx);
                    }
                }

                if (job.getFhjmc().equals(YpscFlowConstant.HJMC_FASH)){
                    SpcySqsxBasic sqsx = spcySqsxBaiscService.getById(shjList.get(0).getFpid());
                    if (sqsx != null) {
                        sqsx.setFcyfazt("否");
                        spcySqsxBaiscService.updateById(sqsx);
                    }
                }

                if (job.getFhjmc().equals(YpscFlowConstant.HJMC_SP_FASH)){
                    SpcySqsxBasic sqsx = spcySqsxBaiscService.getById(shjList.get(0).getFpid());
                    if (sqsx != null) {
                        sqsx.setFspfazt("否");
                        spcySqsxBaiscService.updateById(sqsx);
                    }
                }

                spcySqsxJobService.removeById(id);
                return dealDelNodeJob(id);
            }
        }
        return id;
    }


    @Log(title = "科室内部转办流程任务")
    @ApiOperation(value = "科室内部转办流程任务")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(value = "jobid",name = "当前流程任务jobid",required = true),
            @ApiImplicitParam(value = "ksfl",name = "选择科室分类",required = true)
    })
    @PostMapping(value = "innerChangeFlowJob")
    public HttpResult<?> innerChangeFlowJob(@RequestBody Map<String,String> map){
        String jobid = map.get("jobid");
        String fywflcode = map.get("ksfl");

        if (StringUtils.isBlank(jobid)){
            return HttpResult.error("当前流程任务id不能为空");
        }
        if (StringUtils.isBlank(fywflcode)){
            return HttpResult.error("请选择需要转办的科室");
        }

        CurrentUserVo currentUser = GetCurrentUserUtils.getCurrentUser();
        if (currentUser == null){
            return HttpResult.error("登录已失效，请重新登录");
        }

        SpcySqsxJob job = spcySqsxJobService.getById(jobid);
        if (job == null){
            return HttpResult.error("当前流程任务不存在，请刷新重试");
        }
        Map<String, Object> jobMap = ObjectToMapUtils.objectToMap(job);

        Map slhjNodeDbr = busService.getSlhjNodeDbr(fywflcode);
        List<AgentVo> agentVos = (List<AgentVo>)slhjNodeDbr.get("nextNodeDbrList");
        String dbrid = "";
        String dbr = "";
        if (CollectionUtils.isNotEmpty(agentVos)){
            List<String> dbrIdList = agentVos.stream().map(AgentVo::getDbrid).collect(Collectors.toList());
            List<String> dbrList = agentVos.stream().map(AgentVo::getDbr).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(dbrIdList)) {
                dbrid = StringUtils.join(dbrIdList, ",");
            }
            if (CollectionUtils.isNotEmpty(dbrList)) {
                dbr = StringUtils.join(dbrList, ",");
            }
        }

        String sqsxid = job.getFpid();
        SpcySqsxBasic sqsx = spcySqsxBaiscService.getById(sqsxid);
        if (sqsx != null){
            String oldYwfl = sqsx.getFywflcode();
            if (StringUtils.isNotBlank(fywflcode) && fywflcode.equals(SpcyConstant.YWFL_CODE_YLQX)){
                sqsx.setFscms(SpcyConstant.SQSX_SCMS_SCJCANBJSSC);
                sqsx.setFsplx(SpcyConstant.Sp_type_Ns);

            }else if (StringUtils.isNotBlank(fywflcode) && fywflcode.equals(SpcyConstant.YWFL_CODE_YPZC)){
                sqsx.setFscms(SpcyConstant.SQSX_SCMS_SCJCANBJSSC);
                sqsx.setFsplx(SpcyConstant.Sp_type_Ns);

            }else if (StringUtils.isNotBlank(fywflcode) && fywflcode.equals(SpcyConstant.YWFL_CODE_HZP)){
                sqsx.setFscms(SpcyConstant.SQSX_SCMS_SCJCANBJSSC);
                sqsx.setFsplx(SpcyConstant.Sp_type_Ns);

            }else if (StringUtils.isNotBlank(fywflcode) && fywflcode.equals(SpcyConstant.YWFL_CODE_YPSC)){
                sqsx.setFscms(SpcyConstant.SQSX_SCMS_XCJC);

            }else if (StringUtils.isNotBlank(fywflcode) && fywflcode.equals(SpcyConstant.YWFL_CODE_YPJY)){
                sqsx.setFscms(SpcyConstant.SQSX_SCMS_XCJC);

            }else if (StringUtils.isNotBlank(fywflcode) && fywflcode.equals(SpcyConstant.YWFL_CODE_YPZCLC)){
                sqsx.setFscms(SpcyConstant.SQSX_SCMS_SCJCANBJSSC);
                sqsx.setFsplx(SpcyConstant.Sp_type_Ns);
            }

            sqsx.setFywflcode(fywflcode);
            sqsx.setFywflname(SpcyConstant.getYwclNameByCode(fywflcode));
            spcySqsxBaiscService.updateById(sqsx);

            String lognr = "转办事项，[事项名称]为【"+sqsx.getFsxmc()+"】;[申请单号]为【"+sqsx.getFsqdbh()+"】" +
                    "转给从【"+SpcyConstant.getYwclNameByCode(oldYwfl)+"】转给["+SpcyConstant.getYwclNameByCode(fywflcode)+"];";
            spcyLogService.addLogs(job.getFhjmc(),lognr,sqsxid,LogConstant.LOGS_SQSX_BASIC,SpcyConstant.LOGS_SYS_TYPE_TJ);
        }

        FlowConstant flowConstant = SpcyConstant.getFlowConstant(fywflcode);
        String flowName = flowConstant.getFlowName();
        job.setFlcmc(flowName); // 流程名称
        job.setFdbrid(dbrid);
        job.setFdbr(dbr);
        job.setFfssj(new Date());
        job.setFfsrid(currentUser.getId());
        job.setFfsrmc(currentUser.getName());
        spcySqsxJobService.updateById(job);

        String jobLog = "内部转办流程：";
        jobLog += LogUtils.BeanModifyMsg(job,jobMap);
        spcyLogService.addLogs(job.getFhjmc(),jobLog,sqsxid,LogConstant.LOGS_SQSX_BASIC,SpcyConstant.LOGS_SYS_TYPE_TJ);

        return HttpResult.ok("转办成功");
    }



    /********************************     以下为旧的方法    ********************************************/
    /**
     * 现场检查+技术审评模式-退回上一个环节
     * @param map
     * @return
     */
    public HttpResult<?> returnUpperScSpFlowJob(@RequestBody Map<String,String> map){
        String jobid = map.get("jobid");  // 当前流程任务id
        String opinion = map.get("opinion"); // 退回意见
        String shjid = map.get("shjid"); // 退回的环节id

        CurrentUserVo currentUser = GetCurrentUserUtils.getCurrentUser();
        if (currentUser == null){
            return HttpResult.error("登录已失效，请重新登录");
        }
        SpcySqsxJob job = spcySqsxJobService.getById(jobid);
        // 待办-获取上一个环节id
        SpcySqsxJob syhjJob = spcySqsxJobService.getById(shjid);
        if (job == null){
            return HttpResult.error("当前流程任务不存在");
        }
        if (syhjJob == null){
            return HttpResult.error("当前选择退回的环节不存在");
        }
        // 办理状态 - 待办
        if (StringUtils.isNotBlank(job.getFblzt()) && (job.getFblzt().equals(SpcyConstant.BLZT_DB)
                || job.getFblzt().equals(SpcyConstant.BLZT_TH))) {

            SpcySqsxBasic sqsx = spcySqsxBaiscService.getById(job.getFpid());
            String fscms = sqsx.getFscms(); // 审查模式
            String currentNode = job.getFhjmc(); // 当前环节名称
            boolean scmsDel = false; // 审查模式- 查验+审评 是否可以删除流程
            boolean qtDel = false;
            String oldshjid = job.getFsyhjid(); // 当前流程上环节

            // 综合审查
            if (currentNode.equals(YlqxFlowConstant.HJMC_ZHSC)){
                // 审查模式- 查验+审评
                if (fscms.equals(SpcyConstant.SQSX_SCMS_SCJCANBJSSC)){
                    // 现场检查
                    if (syhjJob.getFhjmc().equals(YpscFlowConstant.HJMC_XCJC)){
                        sqsx.setFcywczt("否");
                        spcySqsxBaiscService.updateById(sqsx);

                    }
                    // 技术审评
                    if (syhjJob.getFhjmc().equals(YpscFlowConstant.HJMC_JSSP)){
                        sqsx.setFspwczt("否");
                        spcySqsxBaiscService.updateById(sqsx);
                    }
                    if (sqsx.getFcywczt().equals("否") && sqsx.getFspwczt().equals("否")){
                        scmsDel = true;
                    }
                }else {
                    qtDel = true;
                    scmsDel = true;
                }

            }else {
                qtDel = true;
                scmsDel = true;
            }
            // 如果 当前 流程上环节与 选择 退回的环节 相等 则删除.否则不等，则修改办理状态
            if (qtDel && !oldshjid.equals(shjid)) {
//                String del = this.dealDelNodeJobInScms(shjid);
            }
            syhjJob.setFthyj(opinion);
            syhjJob.setFfssj(new Date());
            syhjJob.setFblzt(SpcyConstant.BLZT_TH);
            syhjJob.setFfsrid(currentUser.getId());
            syhjJob.setFfsrmc(currentUser.getName());
            spcySqsxJobService.updateById(syhjJob); // 将选中的环节改退回状态

            // 审查模式- 查验+审评
            if (fscms.equals(SpcyConstant.SQSX_SCMS_SCJCANBJSSC)) {
                if (scmsDel) {
                    spcySqsxJobService.removeById(jobid); // 删除当前流程任务待办                    }
                }
            }else {
                spcySqsxJobService.removeById(jobid); // 删除当前流程任务待办
            }

        }

        String logNr = "退回上一环节: 从["+job.getFhjmc()+"]退回到["+syhjJob.getFhjmc()+"];【退回意见】为["+opinion+"]";
        spcyLogService.addLogs(job.getFhjmc(),logNr,job.getFpid(), LogConstant.LOGS_SQSX_JOB,SpcyConstant.LOGS_SYS_TYPE_TH);

        return HttpResult.ok("退回成功");
    }

    /** 递归删除当前流程任务父级的所有流程任务(现场检查+技术审评) */
    public String dealDelNodeJobInScms(String shjid){
        String id = "";
        // 查询上环节流程任务
        List<SpcySqsxJob> shjList = spcySqsxJobService.list(new LambdaQueryWrapper<SpcySqsxJob>().eq(SpcySqsxJob::getFsyhjid, shjid));
        if (CollectionUtils.isNotEmpty(shjList)){
            // 循环删除任务
            for (SpcySqsxJob job : shjList) {
                id = job.getId();

                // 查验方案审核
                if (job.getFhjmc().equals(YpscFlowConstant.HJMC_FASH)) {
                    SpcySqsxBasic sqsx = spcySqsxBaiscService.getById(job.getFpid());
                    sqsx.setFcyfazt("否");
                    spcySqsxBaiscService.updateById(sqsx);
                }

                // 审评方案审核
                if (job.getFhjmc().equals(YpscFlowConstant.HJMC_SP_FASH)) {
                    SpcySqsxBasic sqsx = spcySqsxBaiscService.getById(job.getFpid());
                    sqsx.setFspfazt("否");
                    spcySqsxBaiscService.updateById(sqsx);
                }

                // 现场检查
                if (job.getFhjmc().equals(YpscFlowConstant.HJMC_XCJC)) {
                    SpcySqsxBasic sqsx = spcySqsxBaiscService.getById(job.getFpid());
                    sqsx.setFcywczt("否");
                    spcySqsxBaiscService.updateById(sqsx);
                }

                // 技术审评
                if (job.getFhjmc().equals(YpscFlowConstant.HJMC_JSSP)) {
                    SpcySqsxBasic sqsx = spcySqsxBaiscService.getById(job.getFpid());
                    sqsx.setFspwczt("否");
                    spcySqsxBaiscService.updateById(sqsx);
                }

                spcySqsxJobService.removeById(id);
                return dealDelNodeJob(id);  // 递归调用，上环节删除流程任务
            }
        }
        return id;
    }





}
